import {reqCartList,reqDeleteCartById,reqUpdateCheckedByid} from '@/api';
const state = {
    cartlist:[]
};
const mutations = {
     //获取购物车列表数据
    GETCARTLISR(state, cartlist){
        state.cartlist = cartlist;
    }
};
const actions = {
    //获取购物车列表数据
    async getCartLis({ commit}){
        let result = await reqCartList();
        if(result.code == 200){
            commit('GETCARTLISR', result.data);
        }
    },
    //删除购物车某一个商品
    async  deleteCartListBySkuId({commit},skuId){
        let result = await reqDeleteCartById(skuId);
        if(result.code == 200){
            return "ok";
        }else{
            return Promise.reject(new Error("faile"));
        }
    },
    //修改购物车某一个商品的选中状态
    async updateCheckedById({commit}, {skuId, isChecked}){
      let result = await reqUpdateCheckedByid(skuId, isChecked);
      if(result.code == 200){
        return "ok";
      }else{
        return Promise.reject(new Error('faile'));
      }
    },
    //删除全部勾选的产品
    deleteAllCheckedCart({dispatch, getters}){
        //context: 小仓库 里面有，commit【提交 mutations修改state】 getters【计算属性】 dispatch【派发 action 】 state【当前仓库数据】
        //获取购物车中全部的产品(是一个数组)
        let PromiseAll = [];
        getters.cartlist.cartInfoList.forEach(item => {
            let promise = item.isChecked == 1? dispatch('deleteCartListBySkuId',item.skuId):'';
            //将每一次返回的Promise添加到数组中
            PromiseAll.push(promise);
        });
        //只要全部的[p1,p2,....]都返回成功，返回结果即为成功
        //如果有一次失败，返回即为失败结果
        return Promise.all(PromiseAll);
    },
    //修改全部商品的状态
    updateAllCartIsChecked({dispatch, state},isChecked){
        //数组
        let promiseAll = [];
        state.cartlist[0].cartInfoList.forEach((item)=>{
            let promise = dispatch("updateCheckedById",{
                skuId:item.skuId,
                isChecked,
            })
            promiseAll.push(promise);
        })
        //最终返回的结果
        return Promise.all(promiseAll);
    }
}
//简化数据
const getters = {
    cartlist(state){
       return state.cartlist[0] || {};
    }
};

export default{
    state,
    mutations,
    actions,
    getters,
}